<?php
/**
 * Created by PhpStorm.
 *
 * Author : Traveler.
 * Time   : 2019/12/5 14:05
 * Company: Inner Mongolia Zhengzhi Network Technology Co., Ltd
 */

namespace app\admin\model;


use app\admin\BaseModel;

class Menu extends BaseModel
{
    /**
     * 数据表名称
     * @var string
     */
    protected $table = 'ibms_menu';

    /**
     * 查询字段
     * @var array
     */
    protected $query = [
        'id'     => '=',
        'name'   => 'like',
        'status' => '=',
    ];

    /**
     * (静态)获取当前菜单列表(根据当前用户权限筛选)
     * @return array
     */
    public static function getCurrentMenu()
    {
        $where  = ['type' => 0, 'status' => 1, 'delete_time' => 0];
        $hidden = ['flags', 'type', 'sort', 'status', 'delete_time', 'create_time', 'update_time'];

        // 超级管理员角色不受限制
        if (SUPERADMIN_ROLE_ID == session('admin_info')['role_id']) {
            $menu = static::where($where)->hidden($hidden)->order('sort', 'ASC')->select()->toArray();
        } else {
            $nodes = session('?admin_info') ? explode(',', session('admin_info')['role']['nodes']) : [];
            $menu = static::where($where)->whereIn('id', $nodes)->hidden($hidden)->order('sort', 'ASC')->select()->toArray();
        }

        return generateTree($menu);
    }

    /**
     * (静态)获取表格渲染数据
     * @param array $param     请求参数
     * @param bool  $isdeleted 删除标记
     * @return array
     */
    public static function getMenuTable(array $param = [], bool $isdeleted = false)
    {
        $model  = new static;
        $where  = [['delete_time', $isdeleted ? '>' : '=', 0]];
        $filter = $model->filterParam($param, $where);

        $data = $model->where($filter['where'])->page($filter['page'], $filter['limit'])->select()->toArray();

        return [
            'data'  => formatMenu($data),
            'count' => $model->where($filter['where'])->count()
        ];
    }

    /**
     * (静态)获取所有有效的菜单
     * @return array
     */
    public static function getValidMenu()
    {
        $where = ['type' => 0, 'status' => 1, 'delete_time' => 0];

        return formatMenu(static::where($where)->select()->toArray());
    }

    /**
     * 获取器：展开状态
     * @param mixed $value
     * @return bool
     */
    public function getSpreadAttr($value)
    {
        return (bool)$value;
    }

    /**
     * 获取器：选中状态
     * @param mixed $value
     * @return bool
     */
    public function getIsCheckAttr($value)
    {
        return (bool)$value;
    }
}